﻿using MyPaint.Models;
using PP.PaintLib;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace MyPaint
{
    public partial class MainForm : Form
    {
        #region 字段

        private ToolTip toolTip;
        private Stopwatch stopwatch;

        private DrawBoard drawingBoard; //底层画板
        private Button preButton;  //上一个被选择工具
        private TextBox postTxtWrite;//临时编辑文本框
        private ColorDialog colorDialog; //颜色框
        private OpenFileDialog openFileDialog; //打开文件
        private SaveFileDialog saveFileDialog; //保存文件

        private PPFileInfo myFileInfo;

        private string imagePath = "D://paint.png";//保存图片路径
        private Image targetImage = null;

        private FrmImageSetting frmImageSetting;
        private int ICONHeight, ICONWidth; //ICO高度，宽度
        private int GIFHeight, GIFWidth; //GIF高度，宽度

        private bool isMouseDrawing = false;//标记是否使用鼠标绘图

        /// <summary>
        /// 退出时最小化
        /// </summary>
        private bool isExitToMiniMode => 
            Convert.ToBoolean(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["isExitToMiniMode"].Value);

        private NotifyIcon notifyIcon;
        private FrmEatColor frmEatColor;
        private FrmHistory frmHistory;
        private FrmScreenSnap frmScreenSnap;
        private FrmImageProperty frmImageProperty;
        private FrmSettings frmSettings;
        private FrmMoreFunctionTo frmMoreFunctionTo;

        #endregion

        #region 系统热键注册（解决程序窗体不显示/不激活时会出现快捷键不生效的问题）

        private const int WM_CREATE = 0x1; //窗口消息-创建
        private const int WM_DESTROY = 0x2; //窗口消息-销毁
        private const int AltS_Id = 786; //Alt+S的消息id 可自定义
        private const int AltC_Id = 787; //Alt+C的消息id 可自定义

        /// <summary>
        /// 处理系统键盘消息
        /// </summary>
        /// <param name="m">消息体</param>
        protected override void WndProc(ref Message m)
        {
            if (MouseButtons == MouseButtons.Right)//不响应非客户区域的右键
                return;

            base.WndProc(ref m);
            switch (m.WParam.ToInt32())
            {
                case WM_CREATE:
                    PPWin32.HotKey.RegisterHotKey(this.Handle, AltS_Id, PPWin32.HotKey.KeyModifiers.Alt, Keys.S);
                    PPWin32.HotKey.RegisterHotKey(this.Handle, AltC_Id, PPWin32.HotKey.KeyModifiers.Alt, Keys.C);
                    break;
                case WM_DESTROY:
                    PPWin32.HotKey.UnregisterHotKey(this.Handle, AltS_Id);
                    PPWin32.HotKey.UnregisterHotKey(this.Handle, AltC_Id);
                    break;
                case AltS_Id:
                    M_KeyDown(null, new KeyEventArgs(Keys.Alt | Keys.S));
                    break;
                case AltC_Id:
                    M_KeyDown(null, new KeyEventArgs(Keys.Alt | Keys.C));
                    break;
                default:
                    break;
            }
        }

        #endregion

        public MainForm()
        {
            InitializeComponent();

            #region HotKey - 快捷键

            this.ImageNew.ShortcutKeys = (Keys)(Keys.Control | Keys.N);
            this.ImageSaveTo.ShortcutKeys = (Keys)(Keys.Control | Keys.S);

            this.KeyPreview = true;
            this.KeyDown += M_KeyDown;

            #endregion

            this.AppVersion.Text = $"版本：{Assembly.GetExecutingAssembly().GetName().Version}";

            this.components = new System.ComponentModel.Container();
            toolTip = new ToolTip(this.components);
            toolTip.SetToolTip(ValueChangeBar, $"高斯模糊半径：{ValueChangeBar.Value}");

            this.ShowInTaskbar = false; // 不在任务栏中显示
            this.WindowState = FormWindowState.Minimized; // 最小化窗口
            this.Hide();

        }

        private void M_Load(object sender, EventArgs e)
        {
            this.FormClosing += M_FormClosing;

            //界面绘图事件
            Board.Paint += Board_Paint;
            Board.MouseDown += Board_MouseDown;
            Board.MouseUp += Board_MouseUp;
            Board.MouseMove += Board_MouseMove;
            Board.AllowDrop = true;
            Board.DragDrop += Board_DragDrop;
            Board.DragEnter += Board_DragEnter;

            //初始界面基本信息
            myFileInfo = new PPFileInfo()
            {
                unit = Unit.Pixel,
                picBoxSize = Board.Size
            };

            drawingBoard = new DrawBoard(this.Board);
            InitUI();
            btnDraw_Click(null, null);
            colorDialog = new ColorDialog();// 创建颜色选择对话框

            openFileDialog = new OpenFileDialog();// 创建打开文件对话框
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "图片|*.jpg; *.jpeg; *.png; *.bmp; *.jfif;";
            openFileDialog.DefaultExt = ".png";
            openFileDialog.AddExtension = true;
            openFileDialog.RestoreDirectory = true;

            saveFileDialog = new SaveFileDialog();// 创建保存文件对话框
            saveFileDialog.Filter = "图片|*.jpg; *.jpeg; *.png; *.bmp; *.jfif;";
            saveFileDialog.DefaultExt = ".png";
            saveFileDialog.AddExtension = true;
            saveFileDialog.RestoreDirectory = true;

            //菜单-文件
            this.ImageNew.Click += MenuCommand;//新建，清理画布事件            
            this.ImageOpen.Click += MenuCommand;//打开图片事件           
            this.ImageSaveTo.Click += MenuCommand;//保存图片事件
            this.ImageSaveAs.Click += MenuCommand;//另保存图片事件
            this.ImageSetWinBackGround.Click+= MenuCommand;//设置桌面壁纸
            this.ImageProperty.Click+= MenuCommand;//设置桌面壁纸
            this.AboutMyPaint.Click += MenuCommand;//关于画图
            this.Exit.Click += MenuCommand;//退出

            //菜单-编辑
            this.ImageUnDo.Click += MenuCommand;//新建，清理画布事件    
            this.ImageReDo.Click += MenuCommand;//新建，清理画布事件    

            //菜单-查看
            this.ImageHistory.Click += MenuCommand;//新建，清理画布事件    

            //菜单-工具
            this.ICOSizeSetting.Click += MenuCommand;//图片转ICO-ICO设置
            this.ChangeToICO.Click += MenuCommand;//图片转ICO-选择转化        
            this.GIFSizeSetting.Click += MenuCommand;//图片转GIF-GIF设置
            this.ChangeToGIF.Click += MenuCommand;//图片转GIF-选择转化
            this.EatColorTo.Click += MenuCommand;//取色笔
            this.SnapTo.Click += MenuCommand;//截图
            this.MoreFunctionTo.Click += MenuCommand;//截图

            //菜单-效果
            this.GaussianBlur.Click += MenuCommand; //高斯模糊
            this.InvertedColorBar.Click += MenuCommand;//底片（反色）
            this.BlackAndWhiteBar.Click += MenuCommand;//黑白
            this.ReliefBar.Click += MenuCommand;//浮雕
            this.SoftenBar.Click += MenuCommand;//柔化
            this.SharpeningBar.Click += MenuCommand;//锐化
            this.AtomizationBar.Click += MenuCommand;//雾化
            this.MosaicBar.Click += MenuCommand;//马赛克
            this.Rotate90Bar.Click += MenuCommand;//旋转-90°
            this.Rotate180Bar.Click += MenuCommand;//旋转-180°
            this.Rotate270Bar.Click += MenuCommand;//旋转-270°

            //菜单-设置
            this.SettingsBar.Click += MenuCommand;//设置

            //滑动条
            this.ValueChangeBar.MouseUp += ModifyImageEffect;//高斯模糊+马赛克

            //选择绘图工具事件
            this.btnLineTo.MouseClick += this.btnDraw_Click;
            this.btnEraser.MouseClick += this.btnDraw_Click;
            this.btnWriting.MouseClick += this.btnDraw_Click;

            //选择绘图图型事件
            this.btnDrawLine.MouseClick += this.btnDraw_Click;
            this.btnDrawTriangle.MouseClick += this.btnDraw_Click;
            this.btnDrawCircle.MouseClick += this.btnDraw_Click;
            this.btnDrawArrow.MouseClick += this.btnDraw_Click;
            this.btnDrawDiamond.MouseClick += this.btnDraw_Click;
            this.btnDrawPentagon.MouseClick += this.btnDraw_Click;
            this.btnDrawRectangle.MouseClick += this.btnDraw_Click;
            this.btnDrawRoundRectangle.MouseClick += this.btnDraw_Click;
            this.btnDrawHexagon.MouseClick += this.btnDraw_Click;

            //设置铅笔宽度事件
            this.cboPenWidth.TextChanged += (curSender, curE) =>
            {
                bool floatParseOK = float.TryParse(cboPenWidth.Text, out var outPutNum);
                if (floatParseOK)
                {
                    drawingBoard.SetPenWidth(outPutNum);
                }
            };

            //选择画笔颜色事件
            this.panelSelPenColor.MouseClick += (cursSender, curE) =>
            {
                // 如果用户点击了“确定”按钮
                if (colorDialog.ShowDialog() == DialogResult.OK)
                {
                    drawingBoard.SetPenColor(colorDialog.Color);
                    // 将 Panel 的背景色设置为用户选择的颜色
                    panelSelPenColor.BackColor = colorDialog.Color;
                }
            };

            //线段平滑处理
            this.chkSmoothMode.CheckedChanged += (cursSender, curE) => 
            {
                drawingBoard.SetSmoothLineMode(this.chkSmoothMode.Checked);
            };


            #region notifyIcon托盘设置

            this.notifyIcon = new NotifyIcon();
            this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
            //设置软件图标
            this.notifyIcon.Icon = this.Icon = Icon.FromHandle(Properties.Resources.logo.GetHicon());
            this.notifyIcon.Visible = true;

            //工具
            MenuItem notifyTools = new MenuItem("工具");
            //吸色笔选项
            MenuItem notifyPaintCalculator = new MenuItem("吸色笔");
            notifyPaintCalculator.Click += EatColorTo_Click;
            notifyTools.MenuItems.Add(notifyPaintCalculator);
            //截图选项
            MenuItem notifyPaintSnap = new MenuItem("截图");
            notifyPaintSnap.Click += (s1, e1) => { M_KeyDown(null, new KeyEventArgs(Keys.Alt | Keys.S)); };
            notifyTools.MenuItems.Add(notifyPaintSnap);

            //打开程序所在位置-菜单项  
            MenuItem notifyOpenAppDir = new MenuItem("打开程序所在位置");
            notifyOpenAppDir.Click += (s1, e1) =>
            {
                Process.Start("explorer", Application.StartupPath);
            };

            //帮助选项
            MenuItem notifyHelp = new MenuItem("帮助");
            notifyHelp.Click += (s1, e1) => { MessageBox.Show("欢迎使用该软件，祝您使用愉快！", "帮助", MessageBoxButtons.OK); };
            //关于选项  
            MenuItem notifyAbout = new MenuItem("关于");
            //退出菜单项  
            MenuItem notifyExit = new MenuItem("退出");
            notifyExit.Click += (s1, e1) => { System.Environment.Exit(0); };//退出程序
            //单击后台图标
            notifyIcon.MouseClick += (s1, e1) =>
            {
                if (e1.Button == MouseButtons.Left)
                {
                    this.WindowState = FormWindowState.Normal; // 最小化窗口
                    this.Show();
                }
            };
            notifyAbout.Click += (s1, e1) => { MessageBox.Show("欢迎使用该软件，祝您使用愉快！", "关于", MessageBoxButtons.OK); };
            ////关联托盘控件  
            MenuItem[] childen = new MenuItem[] { notifyTools, notifyOpenAppDir, notifyHelp, notifyAbout, notifyExit };
            notifyIcon.ContextMenu = new ContextMenu(childen);
            notifyIcon.Text = $"{Application.ProductName} \r\n{Application.ProductVersion}";

            #endregion
        }

        /// <summary>
        /// 用户关闭窗体：隐藏程序或者退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void M_FormClosing(object sender, FormClosingEventArgs e)
        {
            //主界面即将关闭，其他子窗体也都隐藏
            foreach (Form f in Application.OpenForms)
            {
                if (f == this) continue;
                f.Hide();
            }

            if (isExitToMiniMode)
            {
                e.Cancel = true;
                this.Hide();
            }
            else
            {
                notifyIcon.Dispose();
                Environment.Exit(0); //退出程序
            }
        }

        #region flpShapes+flpTools : 绘图图形区域+绘图工具区域

        /// <summary>
        /// 选择绘图图形
        /// </summary>
        /// <param name="sender">Button</param>
        /// <param name="e"></param>
        private void btnDraw_Click(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn == null) return;

            bool isToolType = Enum.GetNames(typeof(DrawType)).Contains(btn.Name.Substring(3));

            switch (btn.Name)
            {
                case "btnDrawLine"://选择线段
                    drawingBoard.SetSelectType(DrawType.Line);
                    break;
                case "btnDrawCircle"://选择圆形
                    drawingBoard.SetSelectType(DrawType.Circle);
                    break;
                case "btnDrawRectangle"://选择矩形
                    drawingBoard.SetSelectType(DrawType.Rectangle);
                    break;
                case "btnDrawRoundRectangle"://选择圆角矩形
                    drawingBoard.SetSelectType(DrawType.RoundRectangle);
                    break;
                case "btnDrawDiamond"://选择菱形
                    drawingBoard.SetSelectType(DrawType.Diamond);
                    break;
                case "btnDrawTriangle"://选择三角形
                    drawingBoard.SetSelectType(DrawType.Triangle);
                    break;
                case "btnDrawArrow"://选择箭头
                    drawingBoard.SetSelectType(DrawType.Arrow);
                    break;
                case "btnDrawPentagon"://选择五边形
                    drawingBoard.SetSelectType(DrawType.Pentagon);
                    break;
                case "btnDrawHexagon"://选择六边形
                    drawingBoard.SetSelectType(DrawType.Hexagon);
                    break;

                case "btnEraser"://选择橡皮擦
                    drawingBoard.SetSelectType(DrawType.Eraser);
                    break;
                case "btnWriting"://文本工具
                    drawingBoard.SetSelectType(DrawType.Writing);
                    break;
                case "btnLineTo"://画线工具
                    drawingBoard.SetSelectType(DrawType.LineTo);
                    break;
                default:
                    break;
            }


            if (preButton != null)
            {
                preButton.BackColor = Color.White;
            }
            preButton = btn;

            btn.BackColor = Color.FromArgb(0, 153, 255);
        }

        #endregion

        #region 鼠标绘图事件

        private void Board_Paint(object sender, PaintEventArgs e)
        {
            if (isMouseDrawing)//限制使用startPoint和endPoint
            {
                // 在窗口上绘制
                drawingBoard.Draw(e.Graphics);
            }
        }

        private void Board_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.Board.Image != null)
                {
                    drawingBoard.RecordHistory((Image)this.Board.Image.Clone());
                }
                
                //编辑文本
                if (preButton?.Name == "btnWriting")
                {
                    drawingBoard.SetSelectType(DrawType.Writing);
                    //已有编辑框时，需要先执行文本绘制 并 清除编辑框 处理
                    if (Board.Controls.Contains(postTxtWrite))
                    {
                        PostTxtWrite_LostFocus(null, null);
                    }
                    else
                    {
                        postTxtWrite = new TextBox();
                        postTxtWrite.ImeMode = ImeMode.NoControl;//需要设置，动态添加的控件-输入法才能切换
                        postTxtWrite.Multiline = true;
                        postTxtWrite.Location = e.Location;
                        postTxtWrite.Size = new Size(200, 50);
                        postTxtWrite.LostFocus += PostTxtWrite_LostFocus;
                        Board.Controls.Add(postTxtWrite);
                    }
                }
                isMouseDrawing = true;//开始调用鼠标绘图
                drawingBoard.SetStartPoint(e.Location);
            }
        }

        /// <summary>
        /// 编辑文本框失去焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PostTxtWrite_LostFocus(object sender, EventArgs e)
        {
            //绘制文本
            drawingBoard.SetText(postTxtWrite.Text);
            // 在Graphics对象上绘制图像
            drawingBoard.Draw();
            // 将绘制的图像显示在PictureBox中
            drawingBoard.ShowImage();

            //清除编辑文本框控件
            Board.Controls.Remove(postTxtWrite);
        }

        private void Board_MouseMove(object sender, MouseEventArgs e)
        {
            // 鼠标移动时记录终点，并重绘窗口
            if (e.Button == MouseButtons.Left)
            {
                drawingBoard.SetEndPoint(e.Location);
                if (Enum.GetNames(typeof(DrawType)).Contains(preButton?.Name.Substring(3)))
                {            
                    // 在Graphics对象上绘制图像
                    drawingBoard.Draw();
                    // 将绘制的图像显示在PictureBox中
                    drawingBoard.ShowImage();
                    drawingBoard.SetStartPoint(e.Location);
                    return;
                }
                Board.Invalidate();
            }
        }

        private void Board_MouseUp(object sender, MouseEventArgs e)
        {
            // 在Graphics对象上绘制图像
            drawingBoard.Draw();
            // 将绘制的图像显示在PictureBox中
            drawingBoard.ShowImage();
            isMouseDrawing = false;//停止调用鼠标绘图
        }

        private void Board_DragDrop(object sender, DragEventArgs e)
        {
            imagePath = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            if(PPImage.IsImage(imagePath))
            {
                this.Board.Image = PPImage.LoadImage(imagePath);
                btnApply_Click(null, null);
                drawingBoard = new DrawBoard(this.Board);
                InitUI();
                //存储图片信息
                myFileInfo = new PPFileInfo()
                {
                    fileInfo = new FileInfo(imagePath),
                    unit = Unit.Pixel,
                    picBoxSize = Board.Size,
                };
            }
            else
            {
                MessageBox.Show("拖入文件不是图片！", "错误");
            }
        }

        private void Board_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        #endregion

        #region 菜单按钮点击事件

        /// <summary>
        /// 菜单按钮点击事件
        /// </summary>
        /// <param name="sender">ToolStripItem</param>
        /// <param name="e"></param>
        private void MenuCommand(object sender, EventArgs e)
        {
            try
            {
                var btn = sender as ToolStripMenuItem;
                if (btn == null) return;

                stopwatch = Stopwatch.StartNew();
                OperationTime.Text = $"正在执行{btn.Text}中...";

                var v = btn.OwnerItem;
                if (v != null && v.Text == "效果")
                {
                    if (this.Board.Image != null)
                    {
                        drawingBoard.RecordHistory((Image)this.Board.Image.Clone());
                    }
                }

                switch (btn.Name)
                {
                    #region 菜单-文件

                    case "ImageNew"://新建，清理画布事件
                        drawingBoard.Clear();
                        imagePath = "D://paint.png";
                        break;
                    case "ImageOpen"://打开图片
                        // 如果用户点击了“确定”按钮
                        if (openFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            imagePath = openFileDialog.FileName;
                            if (PPImage.IsImage(imagePath))
                            {
                                this.Board.Image = PPImage.LoadImage(imagePath);
                                btnApply_Click(null, null);
                                drawingBoard = new DrawBoard(this.Board);
                                InitUI();
                                //存储图片信息
                                myFileInfo = new PPFileInfo()
                                {
                                    fileInfo = new FileInfo(imagePath),
                                    unit = Unit.Pixel,
                                    picBoxSize = Board.Size,
                                };
                            }
                        }
                        break;
                    case "ImageSaveTo"://保存图片     
                    case "ImageSaveAs"://另存为图片
                        MyImageSave(imagePath);
                        break;
                    case "ImageSetWinBackGround"://设置为桌面壁纸
                        bool isFileExit = File.Exists(imagePath);
                        if (!isFileExit)
                        {
                            string path = "D:\\newImage.jpg";
                            var msgBoxResult = MessageBox.Show($"是否保存当前图片，并设置为桌面壁纸?\n默认保存路径为：{path}。", "保存", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                            if (msgBoxResult == DialogResult.Cancel) return;
                            imagePath = path;
                        }
                        if (this.Board.Image == null) return;
                        btnApply_Click(null, null);
                        this.Board.Image.Save(imagePath);
                        PPWin32.SetDeskWallPaper(imagePath);
                        break;
                    case "ImageProperty":
                        frmImageProperty = new FrmImageProperty(myFileInfo);
                        frmImageProperty.ShowDialog();
                        this.Board.Size = myFileInfo.picBoxSize;
                        drawingBoard.ReloadPictures(this.Board, this.Board.Width, this.Board.Height);
                        break;
                    case "AboutMyPaint":
                        MessageBox.Show(
                            PPWin32.GetWallpaperPath(),
                            $"{this.Text} - 桌面壁纸文件路径",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information
                            );
                        break;
                    case "Exit":
                        System.Environment.Exit(0);
                        break;

                    #endregion

                    #region 菜单-编辑

                    case "ImageUnDo":
                        drawingBoard.GoBack();
                        break;
                    case "ImageReDo":
                        drawingBoard.GoForward();
                        break;

                    #endregion

                    #region 菜单-查看
                    case "ImageHistory"://历史记录
                        frmHistory?.Close();
                        frmHistory?.Dispose();
                        frmHistory = new FrmHistory();
                        frmHistory.Show();
                        break;
                    #endregion

                    #region 菜单-工具

                    case "ICOSizeSetting":
                        frmImageSetting = new FrmImageSetting(ICONWidth, ICONHeight);
                        frmImageSetting.FormClosed += FrmSetting_FormClosed;
                        frmImageSetting.ShowDialog();
                        break;
                    case "ChangeToICO":
                        openFileDialog = new OpenFileDialog();
                        openFileDialog.Filter = "图像文件 (*.jpg; *.jpeg; *.png; *.bmp)|*.jpg; *.jpeg; *.png; *.bmp|所有文件|*.*";
                        if (openFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            string filePath = openFileDialog.FileName;
                            string fileExtension = Path.GetExtension(filePath);
                            switch (fileExtension)
                            {
                                case ".png":
                                case ".jpeg":
                                case ".jpg":
                                    bool success = PPICON.SaveAsICON(filePath, ICONWidth, ICONHeight);
                                    if (!success)
                                    {
                                        MessageBox.Show("转换失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        break;
                    case "GIFSizeSetting":
                        frmImageSetting = new FrmImageSetting(GIFWidth, GIFHeight, "PPGIF");
                        frmImageSetting.FormClosed += FrmSetting_FormClosed;
                        frmImageSetting.ShowDialog();
                        break;
                    case "ChangeToGIF":
                        openFileDialog = new OpenFileDialog();
                        openFileDialog.Filter = "动图文件 (*.gif; *.jfif)|*.gif; *jfif|所有文件|*.*";
                        if (openFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            string filePath = openFileDialog.FileName;
                            string fileExtension = Path.GetExtension(filePath);
                            bool success = false;
                            switch (fileExtension)
                            {
                                case ".gif":
                                case ".jfif":
                                    success = PPGIF.SaveAsGIF(filePath, GIFWidth, GIFHeight);
                                    break;
                                case ".diff":
                                    success = PPGIF.SaveAsGIF(filePath, GIFWidth, GIFHeight, "DIFF");
                                    break;
                                default:
                                    break;
                            }
                            if (!success)
                            {
                                MessageBox.Show("转换失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        break;
                    case "EatColorTo":
                        EatColorTo_Click(null, null);
                        break;
                    case "SnapTo":
                        M_KeyDown(null,new KeyEventArgs( Keys.Alt | Keys.S));
                        break;                  
                    case "MoreFunctionTo":
                        frmMoreFunctionTo = new FrmMoreFunctionTo();
                        frmMoreFunctionTo.ShowDialog();
                        break;

                    #endregion

                    #region 菜单-效果

                    case "GaussianBlur"://高斯模糊
                        foreach (ToolStripMenuItem item in GaussianBlur.Owner.Items)
                        {
                            item.Checked = item == GaussianBlur ? !item.Checked : false;
                        }
                        ValueChangeBar.Visible = GaussianBlur.Checked;
                        break;
                    case "InvertedColorBar"://底片（反色）
                        drawingBoard.image = PPImage.NegativeImage(this.Board.Image);
                        drawingBoard.ShowImage();
                        break;
                    case "BlackAndWhiteBar"://黑白
                        drawingBoard.image = PPImage.GrayImage(this.Board.Image, 2);
                        drawingBoard.ShowImage();
                        break;
                    case "ReliefBar"://浮雕
                        drawingBoard.image = PPImage.EmbossmentImage(this.Board.Image);
                        drawingBoard.ShowImage();
                        break;
                    case "SoftenBar"://柔化
                        drawingBoard.image = PPImage.SoftenImage(this.Board.Image);
                        drawingBoard.ShowImage();
                        break;
                    case "SharpeningBar"://锐化
                        drawingBoard.image = PPImage.SharpenImage(this.Board.Image);
                        drawingBoard.ShowImage();
                        break;
                    case "AtomizationBar"://雾化
                        drawingBoard.image = PPImage.AtomizationImage(this.Board.Image);
                        drawingBoard.ShowImage();
                        break;
                    case "MosaicBar"://马赛克
                        foreach (ToolStripMenuItem item in MosaicBar.Owner.Items)
                        {
                            item.Checked = item == MosaicBar ? !item.Checked : false;
                        }
                        ValueChangeBar.Visible = MosaicBar.Checked;
                        break;
                    case "Rotate90Bar"://旋转90度                      
                        drawingBoard.image = PPImage.RotateImage(this.Board.Image, 90);
                        drawingBoard.ShowImage();
                        Board.Size = drawingBoard.image.Size;
                        break;
                    case "Rotate180Bar"://旋转180度
                        drawingBoard.image = PPImage.RotateImage(this.Board.Image, 180);
                        drawingBoard.ShowImage();
                        Board.Size = drawingBoard.image.Size;
                        break;
                    case "Rotate270Bar"://旋转270度
                        drawingBoard.image = PPImage.RotateImage(this.Board.Image, 270);
                        drawingBoard.ShowImage();
                        Board.Size = drawingBoard.image.Size;
                        break;

                    case "BackGroundTransparentBar"://背景透明
                        drawingBoard.image = PPImage.MakeBackTransparentImage(this.Board.Image, this.Board.BackColor);
                        drawingBoard.ShowImage();
                        Board.Size = drawingBoard.image.Size;
                        break;

                    #endregion

                    #region 菜单-设置

                    case "SettingsBar"://高斯模糊
                        frmSettings = new FrmSettings(this);
                        frmSettings.ShowDialog();
                        break;

                    #endregion
                    default:
                        break;
                }

                ShowOperationTime(btn.Text);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="imagePath">保存图片的目录</param>
        private void MyImageSave(string imagePath)
        {
            try
            {
                saveFileDialog.FileName = $"PP.Paint绘图_{DateTime.Now.ToString("yyyyMMddHHmmssff")}.png";
                // 如果用户点击了“确定”按钮
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    imagePath = saveFileDialog.FileName;
                    string fileExten = Path.GetExtension(imagePath);
                    if (ICONWidth > 0 && ICONHeight > 0)
                    {
                        drawingBoard.ReloadPictures(Board, ICONWidth, ICONHeight);
                    }
                    this.Board.Image.Save(imagePath);

                    //存储图片信息
                    myFileInfo = new PPFileInfo()
                    {
                        fileInfo = new FileInfo(imagePath),
                        unit = Unit.Pixel,
                        picBoxSize = Board.Size
                    };
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// 修改图片效果-高斯模糊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ModifyImageEffect(object sender, EventArgs e)
        {
            try
            {
                int value = this.ValueChangeBar.Value;

                ToolStripMenuItem tItem = GaussianBlur.Checked ? GaussianBlur : MosaicBar.Checked ? MosaicBar : null;
                if (tItem == null)
                {
                    return;
                }

                OperationTime.Text = $"正在执行{this.GaussianBlur.Text}(半径:{value})中...";

                stopwatch = Stopwatch.StartNew();
                switch (tItem.Name)
                {
                    case "GaussianBlur":
                        drawingBoard.image = PPImage.GaussianBlurImage(this.Board.Image, value);
                        break;
                    case "MosaicBar":
                        drawingBoard.image = PPImage.MosaicImage(this.Board.Image, value); 
                        break;
                    default:
                        drawingBoard.image = this.Board.Image;
                        break;
                }

                drawingBoard.ShowImage();
                btnApply_Click(null, null);
                toolTip.SetToolTip(ValueChangeBar, $"{tItem.Text}半径：{value}");
                ShowOperationTime(tItem.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        #endregion

        #region Customs

        /// <summary>
        /// 显示耗时
        /// </summary>
        /// <param name="operationName"></param>
        private void ShowOperationTime(string operationName)
        {
            stopwatch.Stop();
            OperationTime.Text = $"执行{operationName}耗时：{stopwatch.ElapsedMilliseconds / 1000}.{stopwatch.ElapsedMilliseconds % 1000}(s/秒)";
        }

        /// <summary>
        /// 还原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReBack_Click(object sender, EventArgs e)
        {
            drawingBoard.image = null;
            if (targetImage == null)
            {
                targetImage = new Bitmap(this.Board.Width, this.Board.Height);
            }

            drawingBoard.image = (Image)targetImage.Clone();
            drawingBoard.ShowImage();
        }

        /// <summary>
        /// 应用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnApply_Click(object sender, EventArgs e)
        {
            targetImage = null;
            targetImage = (Image)this.Board.Image.Clone();

            //PPGIF.ImagesToGIF(targetImage);
        }

        /// <summary>
        /// 设置-窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmSetting_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (frmImageSetting.icoHeight != 0 && frmImageSetting.icoWidth != 0)
            {
                ICONHeight = frmImageSetting.icoHeight;
                ICONWidth = frmImageSetting.icoWidth;
            }

            if (frmImageSetting.gifHeight != 0 && frmImageSetting.gifWidth != 0)
            {
                GIFHeight = frmImageSetting.gifHeight;
                GIFWidth = frmImageSetting.gifWidth;
            }
        }

        /// <summary>
        /// 初始化画板，也要初始化UI
        /// </summary>
        private void InitUI()
        {
            foreach (ToolStripMenuItem item1 in menuStrip.Items)
            {
                if (item1.Name == "EffectToolsBar")
                {
                    foreach (ToolStripMenuItem item2 in item1.DropDownItems)
                    {
                        item2.Checked = false;
                    }
                }
            }
            cboPenWidth.SelectedIndex = 0;
            panelSelPenColor.BackColor = Color.Black;
            chkSmoothMode.Checked = false;
        }

        #endregion

        /// <summary>
        /// 打开取色笔界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EatColorTo_Click(object sender, EventArgs e)
        {
            frmEatColor?.Close();
            frmEatColor?.Dispose();

            frmEatColor = new FrmEatColor();
            frmEatColor.Show();
        }

        /// <summary>
        /// 监控快捷键-截图功能
        /// </summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void M_KeyDown(object sender, KeyEventArgs e)
        {
            //调用截图功能
            if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.S)
            {
                frmScreenSnap?.Close();
                frmScreenSnap?.Dispose();
                frmScreenSnap = new FrmScreenSnap();
                frmScreenSnap.Show();
            }

            //调用取色笔功能
            if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.C)
            {
                EatColorTo_Click(null, null);
            }

            //粘贴剪切板图片
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V)
            {
                var image = Clipboard.GetImage();
                if (image != null)
                {
                    this.Board.Image = image;
                    btnApply_Click(null, null);
                    drawingBoard = new DrawBoard(this.Board);
                    InitUI();
                    //存储图片信息
                    myFileInfo = new PPFileInfo()
                    {
                        fileInfo = new FileInfo(imagePath),
                        unit = Unit.Pixel,
                        picBoxSize = Board.Size,
                    };
                }
            }
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TEST_Click(object sender, EventArgs e)
        {
            openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图像文件 (*.jpg; *.jpeg; *.png; *.bmp)|*.jpg; *.jpeg; *.png; *.bmp|所有文件|*.*";
            openFileDialog.Multiselect = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                openFileDialog.Multiselect = true;
                var imgPaths = openFileDialog.FileNames;
                //基于源文件路径，仅修改后缀名为gif
                string fileDirectory = Path.GetDirectoryName(imagePath);
                string outputPath = Path.Combine(fileDirectory, Path.GetFileNameWithoutExtension(imagePath)) + ".gif";
                bool success = PPGIF.ImagesToGIF(imgPaths, outputPath, 2550, 2550);

                if (!success)
                {
                    MessageBox.Show("转换失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show($"转化成功:！保存位置：{outputPath}", "转化结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }

}
